<template>
    <div class="dhzn_goodssort">
        <!-- 查询 -->
        <div class="dh_g-list">
            <div class="dh_g-l-operate">
                <el-form :inline="true" :model="formInline" class="demo-form-inline">
                    <el-form-item label="产品分类">
                        <el-input v-model="formInline.name" placeholder="填写分类名" clearable></el-input>
                    </el-form-item>
                    <el-form-item label="分类等级" collapse-transition>
                        <el-select v-model="formInline.level" placeholder="选择分类的等级">
                            <el-option v-for="item in classlevel" :key="item.id" :label="item.name" :value="item.id"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="paging=3,currentPage=1,classifylist()">搜索</el-button>
                    </el-form-item>
                </el-form>

            </div>

            <div class="dh_g-l-page">
                <div class="f14 bb1 p10">分页列表</div>

                <!-- 按钮和分类列表 -->
                <div class="p10">
                    <div class="dh_glp-btn">
                        <button type="button" @click="paging=1,currentPage=1;for(var i in formInline)formInline[i]='',classifylist()">分类首页</button>
                        <button type="button" @click="dialogformadd=true,addclassify">添加分类</button>
                    </div>
    
                    <table class="dh_glp-table f14" cellspacing="0" cellpadding="0" border="1">
                        <thead> 
                            <tr>
                                <th>ID</th>
                                <th>分类归属</th>
                                <th>分类等级</th>
                                <th>查看子分类</th>
                                <th>分类名称</th>
                                <th>分类图标<br/><span class="n f12 ff53">(*点击查看大图)</span></th>
                                <th>分类类型</th>
                                <th>所属店铺</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                        <tbody class="dh_glp-t-tbody">
                            <tr v-for="(item,key) in classify" :key="key">
                                <td>{{item.id}}</td>
                                <td>{{item.tid | dependent}}</td>
                                <td>{{classlevel[item.level-1].name}}</td>
                                <td><span @click="soncheck.tid=item.id,soncheck.level=item.level,paging=2,currentPage=1,classifylist()">查看</span></td>
                                <td>{{item.name}}</td>
                                <td>
                                    <el-popover placement="top" popper-class="dh_glp-t-t-popover" trigger="click" v-model="item.visible">
                                        <img :src="item.level===1 ? 'https://ss2.bdstatic.com/70cFvnSh_Q1YnxGkpoWK1HF6hhy/it/u=37453093,1676265439&fm=26&gp=0.jpg' : item.imageurl">
                                        <!-- <img :src="item.logo" alt=""> -->
                                        <img slot="reference" :src="item.level===1 ? 'https://ss2.bdstatic.com/70cFvnSh_Q1YnxGkpoWK1HF6hhy/it/u=37453093,1676265439&fm=26&gp=0.jpg' : item.imageurl">
                                    </el-popover>
                                </td>
                                <td>{{classtype[item.type].name}}</td>
                                <td>{{item.shopId | filtershops}}</td>
                                <td>
                                    <button type="button" class="dh_glpt-t-btn bc4a wh f16" @click="dialogFormVisible=true;for(var i in dialogform)dialogform[i]=item[i],dialogform.key=key"><i title="修改" class="f16 iconfont icon-xiugai"></i>编辑</button>
                                    <button type="button" class="dh_glpt-t-btn bcfd wh f16" @click="didetclassify(item.id,key)"><i title="删除" class="f16 iconfont icon-shanchu"></i>删除</button><!--  -->
                                </td>
                            </tr>
                        </tbody>
                    </table>
                </div>

            </div>
            
            <div>
                <!-- 修改的弹出层弹出层 -->
                <el-dialog title="修改商品分类" :visible.sync="dialogFormVisible" :append-to-body='true' width="450px">								
                    <!-- <h1 class="tc pb20 f16"><span v-if="paging === 5">分类添加</span><span v-else>修改分类</span></h1> -->
                    <el-form ref="form" :model="dialogform" label-width="80px" size="mini">
                        <el-form-item label="上级分类" v-if="dialogform.tid !== 0">
                            <el-select v-model="dialogform.tid" clearable placeholder="请选择添加分类的上级分类">
                                <!-- <el-option label="顶级" :value="0"></el-option> -->
                                <el-option v-for="(item,key) in selectdata" :key="key" :label="item.name" :value="item.id"></el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="分类等级" v-if="dialogform.level !== 1">
                            <el-select v-model="dialogform.level" clearable placeholder="选择分类的等级">
                                <el-option v-for="item in classlevel.slice(1,4)" :key="item.id" :label="item.name" :value="item.id"></el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="分类名称">
                            <el-col :span="10"><el-input v-model="dialogform.name" clearable placeholder="请输入需要创建的分类名称"></el-input></el-col>
                        </el-form-item>

                        <el-form-item label="分类图片">
                            
                            <el-upload 
                                action="/api/file/upload" 
                                ref="upload" 
                                name="files" 
                                :headers="headers" 
                                :limit='1' 
                                list-type="picture-card" 
                                :on-preview="handlePictureCardPreview" 
                                :on-success="handleimg">
                                <i class="el-icon-plus"></i>
                            </el-upload>
                            <el-dialog :visible.sync="dialogVisible"><img width="100%" :src="dialogform.imageurl" alt=""></el-dialog>
                        
                        </el-form-item>

                    </el-form>
                    
                    <span slot="footer">
                        <el-button @click="dialogFormVisible = false" size="mini">取 消</el-button>
                        <el-button type="primary" @click="requestupdate" size="mini">确 定</el-button>  
                    </span>
                </el-dialog>

                <!-- 添加的弹出层弹出层 -->
                <el-dialog title="修改商品分类" :visible.sync="dialogformadd" :append-to-body='true' width="450px">								
                    <!-- <h1 class="tc pb20 f16"><span v-if="paging === 5">分类添加</span><span v-else>修改分类</span></h1> -->
                    <el-form :model="dialogform" ref="dialogform"  :rules="rules" label-width="80px" size="mini">
                        
                        <el-form-item label="分类等级" prop="level">
                            <el-select v-model="dialogform.level" clearable placeholder="选择分类的等级">
                                <el-option v-for="item in classlevel" :key="item.id" :label="item.name" :value="item.id"></el-option>
                            </el-select>
                        </el-form-item>

                        <el-form-item label="上级分类" v-show="dialogform.level>1" prop="tid">
                            <el-select v-model="dialogform.tid" clearable placeholder="请选择添加分类的上级分类">
                                <!-- <el-option label="顶级" :value="0"></el-option> -->
                                <el-option v-for="(item,key) in selectdata" :key="key" :label="item.name+'('+item.level+'级分类)'" :value="item.id" v-show="item.level<dialogform.level && item.level===dialogform.level-1"></el-option>
                            </el-select>
                        </el-form-item>

                        <el-form-item label="分类类型" prop="type">
                            <el-select v-model="dialogform.type">
                                <el-option v-for="item in classtype" :key="item.id" :label="item.name" :value="item.id"></el-option>
                            </el-select>
                        </el-form-item>

                        <el-form-item label="所属店铺" v-if="dialogform.type>0"  prop="shopId">
                            <el-select v-model="dialogform.shopId">
                                <el-option v-for="item in shopsname" :key="item.id" :label="item.name" :value="item.id"></el-option>
                            </el-select>
                        </el-form-item>

                        <el-form-item label="分类名称" prop="name">
                            <el-col :span="10"><el-input v-model="dialogform.name" clearable placeholder="请输入需要创建的分类名称"></el-input></el-col>
                        </el-form-item>

                        <el-form-item label="分类图片" prop="imageurl">  
                            <el-upload 
                                action="/api/file/upload" 
                                v-model="dialogform.imageurl"
                                ref="upload" 
                                name="files" 
                                :headers="headers" 
                                :limit='1' 
                                list-type="picture-card" 
                                :on-preview="handlePictureCardPreview" 
                                :on-remove="handledelete"
                                :on-success="handleimg">
                                <i class="el-icon-plus"></i>
                            <el-dialog :visible.sync="dialogVisible"><img width="100%" :src="dialogform.imageurl" alt=""></el-dialog>
                            </el-upload>
                        </el-form-item>

                    </el-form>
                    
                    <span slot="footer">
                        <el-button @click="dialogformadd = false" size="mini">取 消</el-button>
                        <el-button type="primary" @click="requestadd" size="mini">确 定</el-button>  
                    </span>
                </el-dialog>
            </div>

        </div>

        <div class="dh_g-block mt20">
            <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="currentPage"
                :page-size="pagesize"
                layout="total, prev, pager, next, jumper"
                :total="total">
            </el-pagination>
        </div>

    </div>
</template>

<script>
import axios from "../js/request.js";
import login from "../js/login.js"
// let axios = require('axios')
let that 
export default {
    components: {},
    data() {
        return {
            token: '',
            classify:[],
            headers: '',
            activeIndex: '0',
            currentPage: 1,						//分页的默认页数
            pagesize: 10,                       //单页条数
            total: 0,						   //总条数
            soncheck:{},                       //查看子级
            shopsname: '',
            classlevel: [
                {name:"一级分类",id:1},
                {name:"二级分类",id:2},
                {name:"三级分类",id:3},
                {name:"四级分类",id:4},
            ],
            classtype: [
                {name:"平台商品分类",id:0},
                {name:"店商品铺分类",id:1},
                {name:"平台店铺分类",id:2},
            ],
            formInline: {
                name: '',
                level: '',
            },
            // 弹出层的循环表单
            selectdata:[],
            paging: 1,                       //菜逼方法，根据不同请求的函数赋值，分页根据他的不同状态翻页
            dialogform: {
                id: '',
                tid: '',
                level: '',
                name: '',
                imageurl: '',
                shopId: '',
                type: ''
            },
            rules:{
                tid:[
                    {required:true,message:'请选择上级分类',trigger:'change'}
                ],
                level:[
                    {required:true,message:'请选择风分类等级',trigger:'change'}
                ],
                name:[
                    {required:true,message:'请输入分类名称',trigger:'blur'}
                ],
                imageurl:[
                    {required:true,message:'请输入请上传图片',trigger:'change'}
                ],
                shopId:[
                    {required:true,message:'请选择对应的店铺',trigger:'change'}
                ],
                type:[
                    {required:true,message:'请选择分类类型',trigger:'change'}
                ] 
            },
            dialogVisible: false,           //上传图片的弹出层
            dialogFormVisible: false,       // 修改弹出层
            dialogformadd: false            //添加的弹出层状态
        };
    },
    computed: {},
    watch: {},
    filters: {
        operatetype(state){
            if(state == 1){
					state = "修改"
				}else{
					state = "添加"
				}
				return state
        },
        dependent(tid){
            if(tid === 0){
                tid = "顶级"
            }else{
                that.kindname.forEach((item)=>{
                    tid === item.id ? tid = item.name : '';
                })
            }
            return tid
        },
        switchlevel(level){
            if(level == 1 ){
                level = "一级分类"
            }else{
                level = "二级分类"
            }
            return level
        },

        // 店铺名转换
        filtershops(shops){
            if(that.shopsname !== ""){
                that.shopsname.forEach((item)=>{
                    shops === item.id ? shops = item.name : ''
                })
            }else{}
            return shops
        }
    },
    methods: {

        // 单页条数
        handleSizeChange(val) {
            // console.log(`每页: ${val}条数据`);
            this.pagesize = val;
            that.classifylist()
        },

        //分页的跳页函数
        handleCurrentChange(val) {
            // console.log(`当前页: ${val}`);
            that.currentPage = val;
            that.classifylist()
        },
        
        // 获取产品分类列表
        classifylist(){
            let that = this;
            let data = {current:that.currentPage,size:that.pagesize,level:1};
            for(var t in that.formInline){
                that.formInline[t] !== '' 
                ? data[t] = that.formInline[t]
                : ''
            }
            if(that.paging === 2) {
                data.level=that.soncheck.level+1,data.tid=that.soncheck.tid
            }else{}
            // let updata = JSON.stringify(data)
            axios.request("/kind/list","post",data).then(resp=>{
                console.log(resp)   
                if(resp.data.message === "请求成功"){   
                    resp.data.data.forEach(item=>{
                        item.visible = false;
                    })  
                    that.paging === 1 
                    ? that.kindname = resp.data.data.map((item)=>{
                        return{
                            id: item['id'],
                            name: item['name']
                        }
                    }) : '';      
                    that.classify = resp.data.data;
                    that.total = resp.data.code;
                }else{}                
            })
            .catch( err=> {console.log(err)})
        },

        // 删除
        detclassify(detid,key){
            const that = this;
            this.$confirm('数据删除后无法找回，请再次确认是否是需要删除的数据', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            center: 'true'
            })
            .then(() => {
                // 修改商品分类的请求
                let data = {id:detid};
                let updata = JSON.stringify(data);
                axios.request("/kind/delete","post",data).then(resp=>{
                    console.log(resp)
                    that.classify.splice(key,1)
                })
                .catch( err=> {console.log(err)})
            this.$message({
                    type: 'success',
                    message: '成功删除!'
                });
            })
            .catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });          
            });
        },

        // 拿全部的店铺
        requestshops(){
            axios.request("/shop/list","post",{current:1,size:10000000}).then(resp=>{
                console.log(resp)
                that.shopsname = resp.data.data.map((item)=>{
                    return{
                        id: item['id'],
                        name: item['name']
                    }
                })
            })
        },

        // 获取全部分类，剔除分类等级大于2级的，用于选框的分类等级
        onSubmit(){
            axios.request("/kind/list","post",{current:1,size:10000000}).then(resp=>{
                that.selectdata = resp.data.data.map((item)=>{
                    if(item.level < 3){
                        return{
                            id: item['id'],
                            level: item['level'],
                            name: item['name']
                        }
                    }
                })       
            }).catch( err=> {console.log(err)})
        },

        // 弹出层的函数 
        requestupdate(){
            let data = {name:this.dialogform.name,imageurl:this.dialogform.imageurl,level:this.dialogform.level,type:this.dialogform.type};
            for(var o in data) data[o] === "" ? delete data[o] : '';
            axios.request("/kind/updata","post",data).then(resp=>{
                console.log(resp)
                that.dialogFormVisible = false;
                let key = this.dialogform.key;
                for(var i in data) dialogform[key][i] = data[i];
            })
            .catch( err=> {console.log(err)})
        },

        // 添加分类
        requestadd(){
            let data = {};
            this.$refs.dialogform.validate((valid)=>{
                if(valid){       
                    for(var i in that.dialogform) data[i] = that.dialogform[i];
                    console.log(data)
                    axios.request("/kind/add","post",data).then(resp=>{
                        // console.log(resp)
                        for(var i in this.dialogform) dialogform[i] = "";
                    })
                }else{}
            })
        },

        // 上传图片的回调函数
        handleimg(response,file,fileList){
            console.log(response)
            this.dialogform.imageurl = 'http://dzy.dpyun.site/upload/images/' + response.data[0];
        },

        // 上传图片预览
        handlePictureCardPreview(file) {
            this.dialogImageUrl = file.url;
            this.dialogVisible = true;
        },

        // 上传文件表删除时的钩子
        handledelete(file, fileList){
            // console.log(file, fileList)
            that.dialogform.imageurl = '';
        },

        //拿token
        newtoken(){
            let that = this;
            let axios = require('axios')
			let loguser = JSON.parse(sessionStorage.getItem('updata'))
			let data = {username:loguser.username, password:loguser.password};
            login.login("/getAuthority/manager","post",data).then( resp=> {
                // console.log(resp)
                that.token = resp.data.data;
                sessionStorage.setItem("token", JSON.stringify(resp.data.data))
                that.requestshops()
                that.classifylist()
                that.onSubmit()
                that.headers = {
                    'authorization': `Bearer ${resp.data.data}`
                }
			}).catch( err=> {})
        }

    },
    created() {},
    mounted() {
        let that = this;
        that.newtoken()
    },
    beforeCreate() {
        that = this;
    },
    beforeMount() {},
    beforeUpdate() {},
    updated() {},
    beforeDestroy() {},
    destroyed() {},
    activated() {},
    }
</script>
<style scoped>
    ul,li{ 
        /* padding:0; */
        margin:0;
        list-style:none
    }
    .dhzn_goodssort{
        height: calc(100% - 56px);
        box-sizing: border-box;
        display: flex;
        flex-direction: column;
        justify-content: space-between;
    }
    /* 数据列表 */
    .dh_g-list{
        height: 100%;
    }
    .dh_g-l-operate{
        margin-bottom: 10px;
        padding: 10px;
        background-color: #ffffff;
    }
    .dh_g-l-operate>.el-form>.el-form-item{
        margin: 10px 0;
    }


    /* 分类 */
    .dh_g-l-nav{
        overflow: hidden;
        border-radius: 5px 5px 0 0;
    }
    .dh_g-l-nav>ul.el-menu>li.el-menu-item{
        overflow: hidden;
        font-size: 15px;
    }
    .dh_g-l-n-add{
        display: inline-block;
        vertical-align: middle;
    }
    .el-menu--horizontal>.el-menu-item.is-active>.g84f{
        color: #4ca179;
    }
    .el-menu--horizontal>.el-menu-item.is-active>.red{
        color: #ff0000;
    }



    .dh_glp-btn{
        margin-bottom: 10px;
    }
    .dh_glp-btn>button{
        height: 30px;
        margin-right: 5px;
        font-size: 13px;
        color: #ffffff;
        background-color: #409EFF;
        border-radius: 3px;
    }
    /* 单独定义的添加按钮 */
    .el-menu--horizontal>.dh_g-l-n-icon{
        border: none;
    }
    .dh_g-l-n-icon{
        float: right;
        height: 60px;
        line-height: 60px;
        margin-right: 10px;
        outline: none;
    }
    /* 数据 */
    .dh_g-l-page{
        background-color: #ffffff;
    }
    .dh_glp-table{
        text-align: center;
        width: 100%;
        color: #504f4f;
        background-color: #ffffff;
        border-bottom: 1px solid #e0e0e0;
        border-right: 1px solid #e0e0e0;
        border-spacing: 0;/*去掉单元格间隙*/
        border-collapse: collapse;
    }
    .dh_glp-table th{
        background-color: #eeeeee;
        border-bottom: 1px solid #e0e0e0;
    }
    .dh_glp-table th, .dh_glp-table td{
        min-height: 60px;
        padding: 10px 0;
        border-left:1px solid #e0e0e0;
        border-top:1px solid #e0e0e0;
    } 
    .dh_glp-table tbody tr:hover{
        background-color: #eeeeee;
    }
    /* 图片大小的 */
    .dh_glp-t-tbody tr td img{
        max-width: 120px;
        max-height: 80px;
    }
    /* 左边的图片预览效果 */
    .dh_glp-t-t-popover img{
        max-width: 500px;
        max-height: 500px;
    }
    /* 查看子级分类的样式 */
    .dh_glp-table td span:hover{
        cursor: pointer;
        color:cornflowerblue;
    }
    .dh_glpt-t-btn{
        height: 30px;
        border-radius: 3px;
    }

    /* 弹出层 */
    /* .el-select{
        width: 100%;
    } */

    /* 分页 */
    .dh_g-block{
        text-align: center;
    }
</style>